﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

/*********************************************************
 * 命名空间 MDT.LifeSewagePlatform.Extension.http
 * 接口名称 Httphelper
 * 开发人员：-nhy
 * 创建时间：2022/4/7 17:31:12
 * 描述说明：
 * 更改历史：
 * 
 * *******************************************************/
namespace MDT.LifeSewagePlatform.Extension
{
    public class HttpHelper: IHttpHelper
    {
        #region 
        /// <summary>
        /// 异步下载html
        /// </summary>
        /// <param name="url"></param>
        /// <param name="encoder"></param>
        /// <returns></returns>
        public async Task<string> DownLoadHtmlAsync(string url, Encoding encoder)
        {
            string html = string.Empty;
            try
            {
                HttpClient client = new HttpClient();
                HttpResponseMessage responseMessage = await client.GetAsync(url);
                if (responseMessage.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader streamReader = new StreamReader(await responseMessage.Content.ReadAsStreamAsync(), encoder);
                    html = streamReader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("\t\t" + ex.Message);
                if (ex.InnerException != null)
                {
                    Console.WriteLine("\t\t" + ex.InnerException.Message);
                }
            }
            return html;
        }
        /// <summary>
        /// 同步下载html
        /// </summary>
        /// <param name="url"></param>
        /// <param name="encoder"></param>
        /// <returns></returns>
        public string DownLoadHtml(string url, Encoding encoder)
        {
            string html = string.Empty;
            try
            {
                HttpClient client = new HttpClient();
                
                HttpResponseMessage responseMessage = client.GetAsync(url).Result;
                if (responseMessage.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader streamReader = new StreamReader(responseMessage.Content.ReadAsStream(), encoder);
                    html = streamReader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("\t\t" + ex.Message);
                if (ex.InnerException != null)
                {
                    Console.WriteLine("\t\t" + ex.InnerException.Message);
                }
            }
            return html;
        }
        #endregion
    }
}
